1> read读取控制台输入
① 基本语法
read(选项)(参数)
选项 | 说明 | 参数 | 说明 |
---|---|---|---|
-p | 指定读取值时的提示符 | 变量 | 指定读取值的变量名 |
-t | 指定读取值时等待的时间(秒) |
② 实例
read -t 7 -p "Enter your name " NAME
2> 函数
① 系统函数
a) basename基本语法
basename [string / pathname] [suffix]
basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来
b) 实例1
$ basename /home/hello.txt
hello.txt
$ basename /home/hello.txt .txt
hello
c) dirname 基本语法
dirname 文件绝对路径
从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分)
d) 实例2
$ dirname /home/data/lang.txt
/home/data
3> 自定义函数
① 基本语法
[ function ] fun_name[()]
{
Action;
[return int;]
}
fun_name
② 注意点
- 必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译
- 函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)
③ 实例
#!/bin/bash
function sum()
{
s=0
s=$[ $1 + $2 ]
echo "$s"
}
read -p "Please input the num1: " n1;
read -p "Please input the num2: " n2;
sum $n1 $n2;